package com.itclass.auth.handler.authentication.support;

import cn.hutool.json.JSONUtil;
import com.itclass.auth.authentication.token.AbstractJsonAuthenticationToken;
import com.itclass.auth.authentication.token.supprt.UsernamePasswordLoginAuthenticationToken;
import com.itclass.auth.constant.RedisCacheKeyConstants;
import com.itclass.auth.handler.authentication.AbstractAuthenticationSuccessHandler;
import com.itclass.auth.pojo.db.Result;
import com.itclass.auth.pojo.dto.UserDetailsDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Component
public class JsonAuthenticationSuccessHandler extends AbstractAuthenticationSuccessHandler {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean supports(Class<?> authentication) {
        return AbstractJsonAuthenticationToken.class.isAssignableFrom(authentication);
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

        UserDetailsDTO details = (UserDetailsDTO) authentication.getDetails();

        // 删除该账号的登录失败次数
        stringRedisTemplate.delete(RedisCacheKeyConstants.LOGIN_FAILURE + authentication.getPrincipal());
        // 设置响应内容类型为 JSON
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        // 设置响应字符编码为 UTF-8
        response.setCharacterEncoding("UTF-8");
        Map<String, String> map = new HashMap<>();
        map.put("token", (String) request.getAttribute(RedisCacheKeyConstants.AUTHORIZATION));
        map.put("loginName", details.getName());
        map.put("loginAccount", authentication.getPrincipal().toString());
        // 创建一个包含错误信息的 JSON 对象
        String json = JSONUtil.toJsonStr(Result.ok(map));
        response.getOutputStream().write(json.getBytes(StandardCharsets.UTF_8));
    }
}
